package com.mm.cloth.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 网络工具类
 * 用于检查网络连接状态
 */
public class NetworkUtil {
    
    /**
     * 检查网络是否可用
     * @param context 上下文
     * @return 网络是否可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
        return false;
    }
    
    /**
     * 检查主机是否可达
     * @param host 主机地址
     * @param port 端口
     * @param timeout 超时时间（毫秒）
     * @return 主机是否可达
     */
    public static boolean isHostReachable(String host, int port, int timeout) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Boolean> future = executor.submit(new HostAvailabilityTask(host, port, timeout));
        
        try {
            return future.get(timeout, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            return false;
        } finally {
            executor.shutdown();
        }
    }
    
    /**
     * 主机可用性检查任务
     */
    private static class HostAvailabilityTask implements Callable<Boolean> {
        private final String host;
        private final int port;
        private final int timeout;
        
        public HostAvailabilityTask(String host, int port, int timeout) {
            this.host = host;
            this.port = port;
            this.timeout = timeout;
        }
        
        @Override
        public Boolean call() {
            Socket socket = new Socket();
            try {
                SocketAddress socketAddress = new InetSocketAddress(host, port);
                socket.connect(socketAddress, timeout);
                return true;
            } catch (IOException e) {
                return false;
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    // 忽略关闭异常
                }
            }
        }
    }
} 